package Controller;

import Model.Team;
import View.Window;
import java.io.*;
import java.net.*;
import javax.swing.*;

public class Server implements Runnable {

    private ObjectOutputStream output;
    private ObjectInputStream input;
    private ServerSocket server;
    private Socket connection;
    private Window g;

    public Server(Window g) {
	this.g = g;
    }

    public void runServer() {
	try {
	    server = new ServerSocket(15000);

	    while (true) {

		waitForConnection();

		getStreams();

		processConnection();

		closeConnection();
	    }
	} catch (EOFException eof) {
	    JOptionPane.showMessageDialog(null,"Client closed connection.");
	} catch (IOException io) {
	    System.out.println("I/O Error!");
	}
    }

    private void waitForConnection() throws IOException {
	JOptionPane.showMessageDialog(null,"Waiting other player to connect...");

	connection = server.accept();
	
	JOptionPane.showMessageDialog(null,"Connected!");
    }

    private void getStreams() throws IOException {
	output = new ObjectOutputStream(connection.getOutputStream());
	output.flush();

	input = new ObjectInputStream(connection.getInputStream());
    }

    private void processConnection() throws IOException {
	boolean flag = true;
	Object obj;
	
	do {

	    try {
		obj = input.readObject();
		if(obj.getClass().equals(Team.class)){
		    Team team = (Team)obj;
		    g.Match.setVisitorsTeam(team);
		    g.AfterSimulation();
		}else if(obj.getClass().equals(String.class)){
		    System.out.println("Client> " + (String)obj);
		}else {
		    int i = 0;
		    while (((boolean[]) obj).length > i && 10>i) {
			if (g.Match.getVisitorTeam().isStarting(i) != ((boolean[]) obj)[i]) {
			    g.Match.getVisitorTeam().ChangeStatus(i);
			}
			i++;
		    }
		    g.AfterSimulation();
		}
	    } catch (ClassNotFoundException classNotFound) {
		System.out.println("Wrong object recivied!");
	    }

	} while (flag);
    }

    private void closeConnection() throws IOException {
	JOptionPane.showMessageDialog(null,"Client closed connection.");	
	output.close();
	input.close();
	connection.close();
    }

    public void sendData(Object data) {
	try {

	    output.writeObject(data);
	    output.flush();
	} catch (IOException io) {
	    JOptionPane.showMessageDialog(null, "Can't send your team data!");
	    io.printStackTrace();
	}
    }

    @Override
    public void run() {
	System.out.println("servidor");
	runServer();
    }
}